import React from 'react'
import { Form, Upload, message, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { ossConfig } from '@/services/common'

export default class AliyunOSSUpload extends React.Component {
  state = {
    OSSData: {},
  };

  async componentDidMount() {
    await this.init();
  }

  init = async () => {
    try {
      const OSSData = await ossConfig();
      // console.log('OSSData: ', OSSData);

      this.setState({
        OSSData,
      });
    } catch (error: any) {
      message.error(error);
    }
  };

  onChange = ({ file }) => {
    // console.log('file: ', file);
    if (file.status === "done") {
      if (this.props.setCoverKey) {
        this.props.setCoverKey(file.key);
      }

      // 上传完成之后，如果需要url，那么返回url给父组件
      if (this.props.insertImageUrl) {
        this.props.insertImageUrl(file.url);
      }
      message.success("上传成功");
    }
  };

  /* onRemove = file => {
    const { value, onChange } = this.props;

    const files = value.filter(v => v.url !== file.url);

    if (onChange) {
      onChange(files);
    }
  }; */

  getExtraData = file => {
    // console.log('file: ', file);
    const { OSSData }: any = this.state;

    return {
      key: file.key,
      OSSAccessKeyId: OSSData.accessid,
      policy: OSSData.policy,
      Signature: OSSData.signature,
    };
  };

  beforeUpload = async file => {
    const { OSSData }: any = this.state;
    const expire = OSSData.expire * 1000;

    if (expire < Date.now()) {
      await this.init();
    }

    const dir = 'react/';
    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = Date.now() + suffix;
    file.key = OSSData.dir + dir + Date.now() + suffix;
    file.url = OSSData.host + OSSData.dir + dir + filename;

    return file;
  };

  render() {
    const { value, children, accept, showUploadList }: any = this.props;
    const props = {
      name: 'file',
      accept: accept || '',
      fileList: value,
      action: this.state.OSSData.host,
      listType: "picture",
      maxCount: 1,
      onChange: this.onChange,
      // onRemove: this.onRemove,
      data: this.getExtraData,
      beforeUpload: this.beforeUpload,
      showUploadList,
    };
    return (
      <Upload {...props}>
        {children}
      </Upload>
    );
  }
}